<?php
/**
 * 违规记录控制器
 */
namespace Beerus\Modules\Violation\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\Violation\Actions\DownTemplate;
use Beerus\Modules\Violation\Actions\ImportViolation;
use Doraemon\cache\Designer\DesignerViolation as cDesignerViolation;
use Doraemon\model\DesignerAuth;
use Doraemon\model\Designer;
use Doraemon\model\Member;
use Doraemon\service\Designer\DesignerViolationRecord as sDesignerViolationRecord;
use Doraemon\model\Designer\DesignerViolationRecord as mDesignerViolationRecord;
use Doraemon\service\User;
use Doraemon\tools\FileOSSGoTool;
use Doraemon\tools\Log;
use Doraemon\tools\ParamsCheck;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\MessageBag;
use Encore\Admin\Grid\Tools;

class ViolationController extends Controller {
    const PAGE_SIZE = 20;

    public function designerViolation(Request $request, Content $content) {
        $designerUid = $request->get('designer_uid');
        $identityNumber = $request->get('identity_number');
        $page = $request->get('page', 1);
        $pageSize = $request->get('per_page', self::PAGE_SIZE);
        $condition = [];
        if (!empty($designerUid)) {
            $condition['designer_uid'] = $designerUid;
        }
        if (!empty($identityNumber)) {
            $condition['identity_number'] = $identityNumber;
        }
        $condition['data_status[<]'] = mDesignerViolationRecord::STATUS_DELETE;
        $total = mDesignerViolationRecord::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = mDesignerViolationRecord::select('*', $condition);
        sDesignerViolationRecord::adminFormatList($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->tools(function (Tools $tools) {
                    $tools->append(new ImportViolation());
                });
                $grid->tools(function (Tools $tools) {
                    $sHtml = '<i class="fa fa-plus"></i>
<a class="btn btn-sm btn-success" href="http://down.hhz1.cn/apk/violation.xls?d=202204151520">下载导入模版</a>';
                    $tools->append($sHtml);
                });
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(6, function ($filter) {
                        $filter->equal('designer_uid', '设计师UID')->placeholder('请输入设计师UID');
                    });
                    $filter->column(6, function ($filter) {
                        $filter->equal('identity_number', '身份证号/营业执照号')->placeholder('请输入身份证号/营业执照号');
                    });
                    $filter->expand();
                });


                $grid->column('id', 'ID');
                $grid->column('designer_uid', '设计师UID');
                $grid->column('identity_number', '身份证号/营业执照号');
                $grid->column('designer_nick', '设计师昵称');
                $grid->column('operator_name', '对接运营');
                $grid->column('violation_reason', '违规原因')->width(150);
                $grid->column('punish_type', '处罚方式')->display(function() {
                    $punishType = [];
                    foreach ($this->punish_list as $key => $item) {
                        $index = $key + 1;
                        $punishType[] = "{$index}）{$item['punish_name']}";
                    }
                    return implode('<br>', $punishType);
                });
                $grid->column('punish_unit', '处罚天数/分数')->display(function() {
                    $punishUnit = [];
                    foreach ($this->punish_list as $key => $item) {
                        $index = $key + 1;
                        $punishUnit[] = "{$index}）{$item['punish_unit']}";
                    }
                    return implode('<br>', $punishUnit);
                });
                $grid->column('punish_start_date', '开始时间')->display(function () {
                    $punishStartDate = [];
                    foreach ($this->punish_list as $key => $item) {
                        $index = $key + 1;
                        $punishStartDate[] = "{$index}）{$item['punish_start_date']}";
                    }
                    return implode('<br>', $punishStartDate);
                });
                $grid->column('punish_end_date', '结束时间')->display(function() {
                    $punishEndDate = [];
                    foreach ($this->punish_list as $key => $item) {
                        $index = $key + 1;
                        $punishEndDate[] = "{$index}）{$item['punish_end_date']}";
                    }
                    return implode('<br>', $punishEndDate);
                });
                $grid->column('admin_name', '最后操作人');
                $grid->column('remark', '备注')->width(100)->editable();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableEdit();
                });
            }
        );
        return $content
            ->header('设计师违规记录列表')
            ->row($gridList);
    }

    public function saveDesignerViolationRemark(Request $request, $id) {
        $remark = $request->input('value');
        if (!mDesignerViolationRecord::updateInfo(['remark' => $remark], ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json([
            'status' => true,
        ]);
    }

    public function createDesignerViolation(Request $request, Content $content, $id = 0) {
        $data = [
            'punish_list' => [
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_WARNING],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_RECOMMEND_SCORE],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_UNRECOMMENDED],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_LIST_SEE],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_OFF],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_CANCEL_AUTHENTICATION],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_NOT_ALLOW_RENEW],
                ['punish_type' => sDesignerViolationRecord::PUNISH_TYPE_HIDE_RECOMMEND_WORD, 'is_punish' => 1, 'punish_unit' => sDesignerViolationRecord::PUNISH_TYPE_HIDE_RECOMMEND_WORD_UNIT_DAY],
            ]
        ];
        Admin::script($this->setScript());
        $form = new Form($data);
        $form->text('designer_uid', '设计师UID')->required();
        $form->text('identity_number', '身份证号/营业执照号')->required();
        $form->hidden('designer_type_txt', '身份证号/营业执照号提示信息');
        $form->hidden('designer_type', '设计师身份');
        $form->text('violation_reason', '违规原因')->required();
        $form->table('punish_list', '处罚', function ($table) {
            static $num = -1;
            $table->radio('is_punish', '是否选中')->options([1=>'是', 0=>'否'])->default(0);
            $table->select('punish_type', '处罚方式')
                ->options(sDesignerViolationRecord::PUNISH_TYPE_TXT_LIST)
                ->width(300)
                ->readonly();
            if ($num == 0) {
                $table->date('punish_start_date', '开始时间')->format('YYYY-MM-DD')->width(300)->readonly();
            } else {
                $table->date('punish_start_date', '开始时间')->format('YYYY-MM-DD')->default(date('Y-m-d'))->width(300);
            }
            if ($num == 1) {
                $table->select('dimension', '维度')
                    ->options(sDesignerViolationRecord::RECOMMEND_SCORE_DIMENSION_TXT_LIST)
                    ->width(300);
            } else {
                $table->select('dimension', '维度')->width(300)->disable();
            }
            if ($num == 0 || $num == 5 || $num == 6) {
                $table->text('punish_unit', '天数')->width(300)->readonly();
            } else {
                if ($num == -1) {
                    $table->text('punish_unit', '天数/分数')->width(300);
                } else {
                    $tipTxt = $num == 1 ? '分数-3/-5/-8分' : '天数';
                    $table->text('punish_unit', $tipTxt)->width(300);
                }
            }
            $num ++;
        })->disableCreate()->disableDelete();
        $form->disablePjax();

        $header = '添加违规记录';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '设计师违规记录列表'],
                ['text' => '添加违规记录'],
            )->row($tab);
    }

    /*设置scirpt
    *
    * */
    private function setScript() {
        return <<<SCRIPT
            $('#designer_uid').blur(function() {
                var designerUid = $(this).val();
                // 查询该设计师的身份证号或者营业执照号
                let url = '/admin/Violation/designer/getIdentityNum';
                let params = {
                    designer_uid:$(this).val(),
                };
                $.post(url, params, function (result) {
                    if (result.status == false) {
                        $('#identity_number').val('');
                        $('#identity_number').removeAttr('readonly')
                        $('input[name=designer_type_txt]').val('');
                    } else {
                        $('label[for=identity_number]').text(result.data.designer_type_txt);
                        $('input[name=designer_type_txt]').val(result.data.designer_type_txt);
                        if (result.data.identity_number) {
                            $('#identity_number').val(result.data.identity_number);
                            $('#identity_number').attr('readonly','readonly')
                        } else {
                            console.log(result.data.identity_number);
                            $('#identity_number').val(result.data.identity_number);
                            $('#identity_number').removeAttr('readonly');
                        }
                    }
                });
            });
        
            $(':submit').click(function(e){
                // 判断处罚数据是否正常
                var punishList = new Array();
                $(".checked").each(function(key,val) {
                    var parentItem = $(this).parent().parent().parent().parent().parent().parent();
                    var punishType = $(this).parent().parent().parent().parent().parent().parent().find('.punish_type').attr('data-value');
                    var punishStartDate = parentItem.find('#punish_start_date').val(); // 处罚开始时间
                    var dimension = parentItem.find('.dimension').next().find('.select2-selection__rendered').attr('title'); // 处罚维度
                    if (typeof(dimension) == "undefined") {
                        dimension = '';
                    }
                    var punishUnit = parentItem.find('#punish_unit').val(); // 处罚天数/分数
                    punishList.push({
                        is_punish: $(this).find('input').val(),
                        punish_type: punishType,
                        punish_start_date: punishStartDate,
                        dimension: dimension,
                        punish_unit: punishUnit
                    });
                });
                let url = '/admin/Violation/designer/check';
                let params = {
                    designer_uid:$('#designer_uid').val(),
                    violation_reason:$('#violation_reason').val(),
                    punish_list:punishList,
                    designer_type_txt:$('input[name=designer_type_txt]').val(),
                    identity_number:$('#identity_number').val(),
                };
                var confirmTxt = '';
                $.post(url, params, function (result) {
                    console.log(result)
                    if (result.status == false) {
                        layer.msg(result.message);
                        return false;
                    } else {
                        layer.confirm(result.data.confirm_txt, {
                            btn: ['确定', '取消'],
                            title: result.data.confirm_title,
                            area: ['auto']
                        }, function (index) {
                            layer.close(index);
                            let url = '/admin/Violation/designer/save';
                            let params = {
                                designer_uid:$('#designer_uid').val(),
                                violation_reason:$('#violation_reason').val(),
                                punish_list:punishList,
                                designer_type:$('input[name=designer_type]').val(),
                                identity_number:$('#identity_number').val(),
                            };
                            console.log(params);
                            $.post(url, params, function (result) {
                                console.log(result)
                                if (result.status == true) {
                                    layer.msg(result.message);
                                    setTimeout(function () {
                                        window.location.href = "/admin/Violation/designer";
                                    }, 1000);
                                } else {
                                    layer.msg(result.message);
                                }
                            });
                        });
                    }
                });
            })
        SCRIPT;
    }

    public function saveDesignerViolation(Request $request) {
        $designerUid = $request->post('designer_uid');
        $violationReason = $request->post('violation_reason');
        $identityNumber = $request->post('identity_number');
        $punishList = $request->post('punish_list');
        foreach ($punishList as &$punishItem) {
            if ($punishItem['dimension']) {
                $punishItem['dimension'] = array_search($punishItem['dimension'], sDesignerViolationRecord::RECOMMEND_SCORE_DIMENSION_TXT_LIST);
            } else {
                $punishItem['dimension'] = 0;
            }
        }

        $designerAuthInfo = DesignerAuth::getByUId($designerUid);
        if ($designerAuthInfo['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY) {
            $designerAuthUpdateKey = 'business_license_number';
            $identityNumberText = '营业执照号';
            $maxIdentityNumberLen = DesignerAuth::MAX_BUSINESS_LICENSE_NUMBER_LEN;
        } else {
            $designerAuthUpdateKey = 'id_card_number';
            $identityNumberText = '身份证号';
            $maxIdentityNumberLen = DesignerAuth::MAX_ID_CARD_NUMBER_LEN;
        }
        // 如果是后台填的才需要验证
        if (empty($designerAuthInfo[$designerAuthUpdateKey])) {
            if (strlen($identityNumber) > $maxIdentityNumberLen) {
                return response()->json([
                    'status' => false,
                    'message' => "{$identityNumberText}格式有误"
                ]);
            }
        }
        if (!$designerAuthInfo[$designerAuthUpdateKey]) {
            DesignerAuth::updateInfo($designerUid, [$designerAuthUpdateKey=>$identityNumber]);
        } else {
            $identityNumber = $designerAuthInfo[$designerAuthUpdateKey];
        }
        ParamsCheck::formatListString2Int($punishList);
        if (!sDesignerViolationRecord::addViolationRecord($designerUid, $violationReason, $punishList, $identityNumber, Admin::user()->username)) {
            return response()->json([
                'status' => false,
                'message' => '添加违规记录失败'
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => '添加违规记录成功'
        ]);
    }

    public function checkDesignerViolation(Request $request) {
        $designerUid = $request->post('designer_uid');
        $identityNumber = $request->post('identity_number');
        $designerTypeTxt = $request->post('designer_type_txt');
        $violationReason = $request->post('violation_reason');
        $punishList = $request->post('punish_list');
        if (empty($designerUid) || empty($violationReason) || empty($identityNumber)) {
            return;
        }
        if (!ParamsCheck::isPositiveNumber($designerUid)) {
            return response()->json([
                'status' => false,
                'message' => '设计师uid格式有误'
            ]);
        }
        // 获取设计师认证到期时间
        $designerAuthInfo = DesignerAuth::getByUId($designerUid);
        $isPunishFlag = false;
        $confirmPunishTxt = '';
        static $punishIndex = 0;
        foreach ($punishList as $item) {
            if ($item['is_punish']) {
                $punishStartDate = date('Y/m/d', strtotime($item['punish_start_date']));
                $punishIndex ++;
                $isPunishFlag = true;
                $punishTypeTxt = sDesignerViolationRecord::PUNISH_TYPE_TXT_LIST[$item['punish_type']];
                $punishEndDate = sDesignerViolationRecord::adminGetEndDate($item['punish_type'], $item['punish_start_date'], $item['punish_unit']);
                if ($item['punish_type'] != sDesignerViolationRecord::PUNISH_TYPE_WARNING) {
                    if ($item['punish_start_date'] < date('Y-m-d')) {
                        return response()->json([
                            'status' => false,
                            'message' => "{$punishTypeTxt}的开始时间应不早于当天"
                        ]);
                    }
                }
                if ($item['punish_type'] == sDesignerViolationRecord::PUNISH_TYPE_WARNING) {
                    $confirmPunishTxt .= "{$punishIndex}.{$punishTypeTxt}<br>";
                }
                // 若选择扣减推荐指数分数，则开始时间、维度、扣减分数也必填
                if ($item['punish_type'] == sDesignerViolationRecord::PUNISH_TYPE_RECOMMEND_SCORE) {
                    if (!$item['punish_start_date'] || !$item['dimension'] || $item['punish_unit'] === '') {
                        return response()->json([
                            'status' => false,
                            'message' => '选择扣减推荐指数分数，则开始时间、维度、扣减分数也必填'
                        ]);
                    }
                    if (!in_array($item['punish_unit'], sDesignerViolationRecord::RECOMMEND_SCORE_LEVEL_LIST)) {
                        return response()->json([
                            'status' => false,
                            'message' => '推荐指数分数只支持-3/-5/-8分'
                        ]);
                    }
                    $confirmPunishTxt .= "{$punishIndex}.{$punishTypeTxt}（{$punishStartDate}-{$item['dimension']}{$item['punish_unit']}分）<br>";
                }
                // 若选择平台不推荐/仅列表可见/下架/隐藏一句话推荐，则开始时间、天数也必填
                if (in_array($item['punish_type'],
                    [
                        sDesignerViolationRecord::PUNISH_TYPE_UNRECOMMENDED,
                        sDesignerViolationRecord::PUNISH_TYPE_LIST_SEE,
                        sDesignerViolationRecord::PUNISH_TYPE_OFF,
                        sDesignerViolationRecord::PUNISH_TYPE_HIDE_RECOMMEND_WORD
                    ])) {
                    if (!$item['punish_start_date'] || !$item['punish_unit']) {
                        return response()->json([
                            'status' => false,
                            'message' => '选择平台不推荐/仅列表可见/下架/隐藏一句话推荐，则开始时间、天数也必填'
                        ]);
                    }
                    $confirmPunishTxt .= "{$punishIndex}.{$punishTypeTxt}（{$punishStartDate}-{$punishEndDate}）<br>";
                }
                if ($item['punish_type'] == sDesignerViolationRecord::PUNISH_TYPE_CANCEL_AUTHENTICATION) {
                    if (!$item['punish_start_date']) {
                        return response()->json([
                            'status' => false,
                            'message' => '选择取消认证，则开始时间必填'
                        ]);
                    }
                    $confirmPunishTxt .= "{$punishIndex}.{$punishTypeTxt}（{$punishStartDate}-{$punishEndDate}）<br>";
                }
                if ($item['punish_type'] == sDesignerViolationRecord::PUNISH_TYPE_NOT_ALLOW_RENEW) {
                    if (!$item['punish_start_date']) {
                        return response()->json([
                            'status' => false,
                            'message' => '选择不予续费，则开始时间必填'
                        ]);
                    }
                    // 结束时间就是认证结束时间
                    if (empty($designerAuthInfo) || $designerAuthInfo['auth_status'] != DesignerAuth::STATUS_AUTH_COMPLETE) {
                        return response()->json([
                            'status' => false,
                            'message' => '该设计师不是认证设计师'
                        ]);
                    }
                    $confirmPunishTxt .= "{$punishIndex}.{$punishTypeTxt}（{$punishStartDate}-{$punishEndDate}）<br>";
                }
            }
        }
        // 处罚方式（至少勾选一个）
        if (!$isPunishFlag) {
            return response()->json([
                'status' => false,
                'message' => '处罚方式（至少勾选一个）'
            ]);
        }
        $designerInfo= User::getBasicUserInfo($designerUid);
        if (empty($designerInfo) || $designerInfo['type'] != Member::AUTH_USER_DESIGNER) {
            return response()->json([
                'status' => false,
                'message' => '该设计师不存在'
            ]);
        }
        $confirmTxt = "设计师<span style='color: red'>「{$designerInfo['nick']}」</span>{$designerTypeTxt}:<span style='color: red'>「{$identityNumber}」</span><br>由于<span style='color: red'>{$violationReason}</span>，将受到如下处罚:<br>";
        $confirmTxt .= "<span style='color: red'>$confirmPunishTxt</span>";
        return response()->json([
            'status' => true,
            'message' => 'success',
            'data' => [
                'designer_nick' => $designerInfo['nick'],
                'confirm_title' => '处罚执行后不可修改、撤销，确认执行吗？',
                'confirm_txt' => $confirmTxt,
            ]
        ]);
    }

    public function delDesignerViolation($id) {
        $info = mDesignerViolationRecord::get('*', ['id' => $id]);
        // 单个删除
        if (!mDesignerViolationRecord::updateInfo([
            'data_status' => mDesignerViolationRecord::STATUS_DELETE,
            'admin_name' => Admin::user()->username
        ], ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        // 刷新该用户处罚标签池
        sDesignerViolationRecord::refreshUserPunishTagPool($info['designer_uid'], $id);
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }

    // 获取设计师身份证号/营业执照号
    public function getIdentityNum(Request $request) {
        $designerUid = $request->post('designer_uid');
        if (!ParamsCheck::isPositiveNumber($designerUid)) {
            $identityNumber = '';
            $designerTypeTxt = '身份证号/营业执照号';
        } else {
            // 身份为机构则是营业执照号，否则是身份证号
            $designerAuthInfo = DesignerAuth::getByUId($designerUid);
            if (empty($designerAuthInfo)) {
                $designerTypeTxt = '身份证号/营业执照号';
                $identityNumber = '';
            } else {
                if ($designerAuthInfo['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY) {
                    $identityNumber = $designerAuthInfo['business_license_number'];
                    $designerTypeTxt = '营业执照号';
                } else {
                    $identityNumber = $designerAuthInfo['id_card_number'];
                    $designerTypeTxt = '身份证号';
                }
            }
        }
        return response()->json([
            'status' => 'success',
            'message' => '账号获取成功',
            'data' => [
                'designer_type_txt' => $designerTypeTxt,
                'identity_number' => $identityNumber
            ]
        ]);
    }
}
